import { isMobile } from './deviceDetection.js';

// 摄像头状态变量
let stream = null;
let cameraActive = false;
let currentPhotoData = null;

// 检查摄像头可用性
function checkCameraAvailability(toggleCameraBtn) {
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        toggleCameraBtn.disabled = false;
    } else {
        toggleCameraBtn.disabled = true;
        toggleCameraBtn.title = '您的设备不支持摄像头功能';
    }
}

// 开关摄像头
function toggleCamera(elements) {
    if (cameraActive) {
        stopCamera(elements);
    } else {
        startCamera(elements);
    }
}

// 停止摄像头
function stopCamera(elements) {
    if (!cameraActive) return;

    const { video, shutterBtn, toggleCameraBtn } = elements;
    
    if (stream) {
        stream.getTracks().forEach(track => track.stop());
        stream = null;
    }
    
    video.srcObject = null;
    video.style.display = 'none';
    
    // 隐藏快门按钮
    if (shutterBtn) {
        shutterBtn.style.display = 'none';
    }

    document.querySelector('.video-container').style.display = 'none';
    document.getElementById('selectedImage').style.display = 'none'
    document.getElementById('photoConfirmControls').style.display = 'none';
    document.querySelector('.no-image-placeholder').style.display = 'flex';
    

    resetProbabilityItems();
    
    cameraActive = false;
    
    // 恢复摄像头按钮文本和功能为"打开摄像头"
    toggleCameraBtn.textContent = '打开摄像头';
    toggleCameraBtn.classList.remove('camera-active');
    toggleCameraBtn.style.background = 'linear-gradient(135deg, var(--primary-color), var(--secondary-color))';
}

// 启动摄像头
function startCamera(elements) {
    const { 
        video, 
        toggleCameraBtn, 
        shutterBtn, 
        exampleImageBtn 
    } = elements;

    document.getElementById('backPhotoBtn').style.display = 'none';
    resetProbabilityItems();

    // 停止旧的摄像头流（如果有）
    if (stream) {
        stream.getTracks().forEach(track => track.stop());
        stream = null;
    }

    const constraints = {
        video: {
            facingMode: 'user'
        }
    };

    if (isMobile) {
        constraints.video.width = { ideal: 1920 };
        constraints.video.height = { ideal: 1080 };
    }

    navigator.mediaDevices.getUserMedia(constraints)
        .then((mediaStream) => {
            stream = mediaStream;
            video.srcObject = mediaStream;
            video.style.display = 'block';
            document.querySelector('.video-container').style.display = 'block';
            document.querySelector('.no-image-placeholder').style.display = 'none';

            if (shutterBtn) shutterBtn.style.display = 'flex';
            if (exampleImageBtn) exampleImageBtn.style.display = 'block';

            cameraActive = true;
            toggleCameraBtn.textContent = '关闭摄像头';
            toggleCameraBtn.classList.add('camera-active');

            moveToCamera();
        })
        .catch((err) => {
            console.error('摄像头访问错误:', err);
            alert('无法访问摄像头: ' + err.message);
        });
}

function moveToCamera() {
    if (isMobile) {
        const visualizationContainer = document.querySelector('.visualization-header');
        if (visualizationContainer) {
            visualizationContainer.scrollIntoView({ 
                behavior: 'smooth', 
                block: 'start' 
            });
        }
    }
}

// 拍照功能
function takePhoto(elements) {
    const { video, canvas, shutterBtn } = elements;
    
    if (!cameraActive) return;

    // 触发闪光灯效果
    const flashEffect = document.getElementById('flashEffect');
    flashEffect.classList.add('active');
    
    // 闪光效果结束后移除active类
    setTimeout(() => {
        flashEffect.classList.remove('active');
    }, 500);

    // 保持原始高分辨率采集
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;

    const context = canvas.getContext('2d');
    context.drawImage(video, 0, 0, canvas.width, canvas.height);

    // 新增智能裁剪逻辑
    const croppedCanvas = document.createElement('canvas');
    const targetSize = 384;

    // 计算裁剪区域（保持舌体在画面中央）
    const cropSize = Math.min(canvas.width, canvas.height);
    const sourceX = (canvas.width - cropSize)/2;
    const sourceY = (canvas.height - cropSize)/2;

    // 创建裁剪后的canvas
    croppedCanvas.width = targetSize;
    croppedCanvas.height = targetSize;
    const ctx = croppedCanvas.getContext('2d');
    ctx.drawImage(canvas, 
        sourceX, sourceY, cropSize, cropSize,  // 源图像裁剪区域
        0, 0, targetSize, targetSize          // 目标尺寸
    );

    // 转换为JPEG时提高质量参数（0.8-0.95之间）
    const imageData = croppedCanvas.toDataURL('image/jpeg', 0.9);
    
    // 创建文件名
    const fileName = 'tongue_photo_' + new Date().toISOString().replace(/:/g, '-').replace(/\./g, '-') + '.jpg';
    
    // 暂停视频流（不停止摄像头，只是暂停显示）
    video.pause();
    video.classList.add('video-paused');
    
    // 隐藏快门按钮
    shutterBtn.style.display = 'none';
    // 显示确认/重拍按钮
    document.getElementById('photoConfirmControls').style.display = 'flex';
    document.getElementById('confirmPhotoBtn').style.display = 'block';

    
    // 存储当前拍摄的照片数据，以便确认时使用
    currentPhotoData = {
        imageData: imageData,
        fileName: fileName
    };
    
    return currentPhotoData;
}

// 重置相机状态
function resetCamera(elements) {
    const { video, shutterBtn } = elements;
    
    // 恢复视频流显示
    if (cameraActive) {
        video.play();
        video.classList.remove('video-paused');
        
        // 显示快门按钮
        shutterBtn.style.display = 'flex';
        
        // 隐藏确认/重拍按钮
        document.getElementById('photoConfirmControls').style.display = 'none';
    }
    resetProbabilityItems();
    // if (!cameraActive) {
    //     startCamera(elements);
    // }
}

function clearCamera(elements) {
    const { video, shutterBtn } = elements;
    
    // 恢复视频流显示
    if (cameraActive) {
        video.play();
        video.classList.remove('video-paused');
        
        // 显示快门按钮
        shutterBtn.style.display = 'flex';
        
        // 隐藏确认/重拍按钮
        document.getElementById('no-image-placeholder').style.display = 'flex';
    }
    resetProbabilityItems();
}

function resetProbabilityItems(){
    // 重置所有概率项为0
    const probabilityItems = document.querySelectorAll('.probability-item');
    probabilityItems.forEach(item => {
        const labelElement = item.querySelector('.probability-label');
        const barElement = item.querySelector('.probability-bar');
        const valueElement = item.querySelector('.probability-value');
        
        // 恢复原始标签文本（移除可能的结果文本）
        const originalLabel = labelElement.textContent.split(' - ')[0];
        labelElement.textContent = originalLabel;
        
        // 重置进度条宽度和百分比值
        barElement.style.width = '0%';
        valueElement.textContent = '0%';
    });
}

export { 
    checkCameraAvailability, 
    toggleCamera, 
    stopCamera, 
    moveToCamera,
    takePhoto, 
    resetCamera,
    clearCamera,
    resetProbabilityItems,
    cameraActive,
    currentPhotoData
};